local blaze = require "blaze"
local app = require "app"
local gamelib = require "club.threecard.gamelib"
local SimpleList = require "blaze.ui.widget.SimpleList"
local RoomItem = gamelib.require "UI.RoomLobby.RoomItem"

local GameObjectExtension = CS.Blaze.GameObjectExtension

local log = app.logging.get("RoomLobbyUI")

local M = gamelib.ui.activity()

M.store_watchers = {
    rooms = {
        ["更新房间"] = function(self, store, state, args, init)
            if init and #state.map == 0 then
                return
            end
            
            local rooms = state.map
            self.roomList:fill(rooms)
        end
    }
}

function M:ctor()
    self.res = "club.threecard.gamelib/ui/roomlobby.b:RoomLobbyUI"

    local Footer = require "ui.Lobby.Footer"
    local Header = require "ui.Lobby.Header"
    self.header = Header.new()
    self.header:set_backward_callback(function() self:on_back() end)
    self.footer = Footer.new()

    self.roomList = SimpleList.new()
    self.roomList.create_item = function(_, data, index)
        local ret = RoomItem.new(data)
        ret.res = string.format("club.threecard.gamelib/ui/roomlobby.b:style%s", index)
        return ret
    end

    local chip_anim = require "ui.Widget.chip_anim"
    self.online_bonus_anim = chip_anim.new()
    self.footer.online_bonus.on_collected = function()
        local src = self.footer.online_bonus:get_chip_transform()
        local dst = self.header:get_chip_transform()
        self.online_bonus_anim:play(src, dst, 4)
        app.audio.post("online_bonus:collected")
    end
end

function M.before_route_enter(to, from, next)
    next()
    if #app.store.rooms.state.list == 0 then
        app.kbe.player().room_api:query_room_list()
    end
end

function M:load()
    self:super("load")
    self.roomList:load()
    self.roomList:set_parent(self.room_list_root)
    self.header:load()
    self.header:set_parent(self.header_root, false)
    self.footer:load()
    self.footer:set_parent(self.footer_root, false)
end

function M:on_injected(bind)
    bind("activity.tweener", self.animator)
    bind("shortcut.escape", self.gameobject, self.on_back)
end

function M:on_back()
    if app.router.stack():count() > 1 then
        app.router.back()
    else
        app.game.exit()
    end
end

function M:on_release()
    self.roomList:release()
    self.header:release()
    self.footer:release()
    self.online_bonus_anim:release()
end

return M